const UserDao = require('../dao/userDao');
const OptionDao = require('../dao/optionDao');
const MyOptionDao = require('../dao/myOptionDao');
const TaOptionDao = require('../dao/taOptionDao');
const UserRightsDao = require('../dao/userRightsDao');
const ShareListDao = require('../dao/shareListDao');
const FriendDao = require('../dao/friendDao');
const BlackListDao = require('../dao/blackListDao');
const WeChatPayDao = require('../dao/weChatPayDao');
exports.list = function (params) {
    return new Promise(function (resolve, reject) {
        UserDao.queryUserDetail(masterPool, params)
            .then(function (result) {
                return UserDao.selectUser(masterPool, {params: params, selfInfo: result[0]}, true);
            })
            .then(resolve, reject);
    });
};

// 格式化扣除加好友次数参数
let formatAddNumParams = function (userInfo, params) {
    let count = 0;
    if (params.MyField0) {
        count = 50
    } else if (params.MyField147 || params.MyField148) {
        count = 10
    } else {
        return params
    }
    if (userInfo.FreeAddNum == 1) {
        params.FreeAddNum = 0
    }
    if (userInfo.ShareAddNum > 0 && userInfo.ShareAddNum + userInfo.FreeAddNum >= count) {
        params.ShareAddNum = userInfo.ShareAddNum + userInfo.FreeAddNum - count
    } else {
        params.ShareAddNum = 0
        params.PaidAddNum = userInfo.PaidAddNum - (count - (userInfo.ShareAddNum + userInfo.FreeAddNum))
    }
    return params
}

exports.update = function (params) {
    return new Promise(function (resolve, reject) {
        mysqlHelper.getConn()
            .then(function (conn) {
                conn.openTransaction()
                    .then(function () {
                        return UserDao.queryUser(conn, params)
                            .then(function (result) {
                                console.log(result)
                                let userInfo = result[0];
                                params = formatAddNumParams(userInfo, params)
                                return UserDao.updateUser(conn, params);
                            })
                    })
                    .then(function () {
                        return MyOptionDao.updateMyOption(conn, params)
                    })
                    .then(function () {
                        return TaOptionDao.updateTaOption(conn, params)
                    })
                    .then(function () {
                        return conn.commitTransaction();
                    }, function (err) {
                        conn.rollbackTransaction();
                        throw err;
                    })
                    .then(function () {
                        conn.releaseConn();
                        resolve("更新成功")
                    }, function (err) {
                        console.log(err);
                        conn.releaseConn();
                        reject(err)
                    });
            })
    });
};
exports.pc_update = function (params){
    return UserDao.pc_updateUser(masterPool,params);
};
exports.detail = function (params) {
    return new Promise(function (resolve, reject) {
        let user = {
            userInfo: {},
            userOption: [],
            isBlack: false
        };
        if (params.TaOpenId) {
            BlackListDao.isBlack(masterPool, {openid: params.TaOpenId, BlackOpenId: params.openid})
                .then(function (result) {
                    if (result.length > 0)
                        user.isBlack = true;
                    return UserDao.queryUser(masterPool, {openid: params.TaOpenId});
                })
                .then(function (result) {
                    if (result.length > 0) {
                        user.userInfo = result[0];
                        return OptionDao.queryOption(masterPool, {openid: params.TaOpenId});
                    } else {
                        throw {code: 201, errorInfo: "未找到用户"};
                    }
                })
                .then(function (result) {
                    user.userOption = formatOption(result[0]);
                    return UserDao.getIntegrity(masterPool, {openid: params.TaOpenId});
                })
                .then(function (result) {
                    user.userInfo.Integrity = result[0].Integrity;
                    resolve(user);
                }, reject);
        } else {
            UserDao.queryUser(masterPool, {openid: params.openid})
                .then(function (result) {
                    if (result.length > 0) {
                        user.userInfo = result[0];
                        return OptionDao.queryOption(masterPool, {openid: params.openid});
                    } else {
                        throw {code: 201, errorInfo: "未找到用户"};
                    }
                })
                .then(function (result) {
                    user.userOption = formatOption(result[0]);
                    return UserDao.getIntegrity(masterPool, {openid: params.openid});
                })
                .then(function (result) {
                    user.userInfo.Integrity = result[0].Integrity;
                    resolve(user);
                }, reject);
        }
    });
};
exports.create = function (params) {
    return new Promise(function (resolve, reject) {
        params.Sincerity = 0;
        params.FreeAddNum = 1;
        mysqlHelper.getConn()
            .then(function (conn) {
                conn.openTransaction()
                    .then(function () {
                        return UserDao.getAllUserNumber(conn);
                    })
                    .then(function (num) {
                        params.UserNo = generateUserNo(num);
                        return ShareListDao.queryShare(conn, {openid: params.openid});
                    })
                    .then(function (result) {
                        if (result.length > 0) {
                            // params.ShareAddNum = 5;
                            return UserDao.addShareAddNum(conn, {openid: result[0].ShareOpenId})
                                .then(function () {
                                    return ShareListDao.deleteShare(conn, {openid: params.openid});
                                })
                        } else {
                            return;
                        }
                    })
                    .then(function () {
                        return UserDao.createUser(conn, params);
                    })
                    .then(function (result) {
                        return MyOptionDao.createMyOption(conn, params)
                    })
                    .then(function (result) {
                        return TaOptionDao.createTaOption(conn, params)
                    })
                    .then(function (result) {
                        return UserRightsDao.createRights(conn, {openid: params.openid});
                    })
                    .then(function (result) {
                        return conn.commitTransaction();
                    }, function (err) {
                        conn.rollbackTransaction();
                        throw err;
                    })
                    .then(function () {
                        conn.releaseConn();
                        resolve("创建成功")
                    }, function (err) {
                        console.log(err);
                        conn.releaseConn();
                        reject(err)
                    });
            })
    });
};
exports.pcUserList = function (params) {
    return new Promise(function (resolve, reject) {
        let listData;
        UserDao.pcUserList(masterPool, params, true)
            .then(function (result) {
                listData = result;
                let promiseList = [];
                listData.data.forEach(function (data) {
                    console.log(data);
                    promiseList.push(
                        UserDao.getIntegrity(masterPool, {openid: data.openid})
                            .then(function (integrityResult) {
                                if(integrityResult.length===1) data.Integrity = integrityResult[0].Integrity
                                else data.Integrity = 0;
                                return WeChatPayDao.getLastRechargeFee(masterPool,{openid: data.openid});
                            })
                            .then(function (rechargeResult) {
                                if(rechargeResult.length===1) data.LastRechargeFee = rechargeResult[0].RechargeTotalFee
                                else data.LastRechargeFee = 0;
                            })
                    );
                    promiseList.push(
                        ShareListDao.queryShareByShareId(masterPool, {ShareOpenId: data.openid}).then(function (shareResult) {
                            data.ShareNum = shareResult.length
                        })
                    )
                });
                return Promise.all(promiseList);
            })
            .then(function () {
                return listData;
            })
            .then(resolve, reject);
    });
};
exports.no_register_userList = function (params) {
    return new Promise(function (resolve, reject) {
        UserDao.no_register_selectUser(masterPool, params, true)
            .then(resolve, reject);
    });
};
exports.evaluate = function (params) {
    return new Promise(function (resolve, reject) {
        let userInfo = {};
        UserDao.queryUser(masterPool, {openid: params.TaOpenId})
            .then(function (result) {
                userInfo = result[0];
                if (userInfo.Sincerity != 0 && Math.abs(userInfo.Sincerity - params.Sincerity) >= 40) {
                    return UserDao.queryUser(masterPool, {openid: params.openid})
                        .then(function (myUserInfo) {
                            return UserDao.updateUser(masterPool, {
                                openid: params.openid,
                                Sincerity: myUserInfo[0].Sincerity - 1
                            });
                        })
                        .then(function () {
                            return UserDao.updateUser(masterPool, {
                                openid: params.TaOpenId,
                                Sincerity: (userInfo.Sincerity * userInfo.EvaluateNum + params.Sincerity) / (userInfo.EvaluateNum + 1),
                                EvaluateNum: userInfo.EvaluateNum
                            });
                        })
                } else {
                    return UserDao.updateUser(masterPool, {
                        openid: params.TaOpenId,
                        Sincerity: (userInfo.Sincerity * userInfo.EvaluateNum + params.Sincerity) / (userInfo.EvaluateNum + 1),
                        EvaluateNum: userInfo.EvaluateNum + 1
                    });
                }
            })
            .then(function (result) {
                return FriendDao.updateFriendInfo(masterPool, params);
            })
            .then(resolve('评价成功'), reject);
    });
};
function formatOption(options) {
    let _result = [];
    for (let i = 0; i <= 152; i++) {
        let item = {};
        item["MyField" + i] = options["MyField" + i];
        item["TaField" + i] = options["TaField" + i];
        _result.push(item);
    }
    return _result;
}
function generateUserNo(index) {
    index += 1;
    let userNo = '';
    let overPlus = 8 - (index + '').length;
    for (let i = 0; i < overPlus; i++) {
        userNo += Math.floor(Math.random() * 10);
    }
    return index + userNo;
}